package org.qingke.mail.protal.service;

import org.qingke.mail.cache.CacheContext;
import org.qingke.mail.common.Response;
import org.qingke.mail.domain.TbItemCat;
import org.qingke.mail.protal.common.CatNode;
import org.qingke.mail.protal.common.CatResult;
import org.qingke.mail.util.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;


import java.util.ArrayList;
import java.util.List;

/**
 * 商品分类查询业务接口实现类
 * @author Administrator
 *
 */
@Service("itemCatService")
public class ItemCatServiceImpl extends CacheContext implements ItemCatService {
	         
	@Autowired
	private RestTemplate  restTemplate;
	
	
	@Override
	public CatResult queryByParentId(long parentId) {
		CatResult catResult=new CatResult();
		catResult.setData(getCatList(parentId));
		return catResult;
	}

private List<?> getCatList(long parentId) {
		
		String url = "http://ITEM-SERVICE/itemcat/queryByParentId?parentId="+parentId;
		Response response = restTemplate.getForEntity(url,Response.class).getBody();
		
		//返回值list
		List resultList = new ArrayList<>();
		if(response.isState()){
			//执行查询
			List<TbItemCat> list =(List<TbItemCat>)JsonUtils.jsonToList(JsonUtils.objectToJson(response.getData()), TbItemCat.class);
			//List<TbItemCat> list =(List<TbItemCat>)JsonUtil.fromJson(JsonUtil.toJson(response.getData()), new TypeToken<List<TbItemCat>>() {}.getType());//
			//向list中添加节点
			int count = 0;
			for (TbItemCat tbItemCat : list) {
				//判断是否为父节点
				if (tbItemCat.getIsParent()) {
					CatNode catNode = new CatNode();
					if (parentId == 0) {
						catNode.setName("<a href='/products/"+tbItemCat.getId()+".html'>"+tbItemCat.getName()+"</a>");
					} else {
						catNode.setName(tbItemCat.getName());
					}
					catNode.setUrl("/products/"+tbItemCat.getId()+".html");
					catNode.setItem(getCatList(tbItemCat.getId()));
					
					resultList.add(catNode);
					count ++;
					//第一层只取14条记录
					if (parentId == 0 && count >=14) {
						break;
					}
				//如果是叶子节点
				} else {
					resultList.add("/products/"+tbItemCat.getId()+".html|" + tbItemCat.getName());
				}
			}
		}
		return resultList;
	}
	

}
